package top.codetheory;

import java.util.HashMap;
import java.util.Map;

public class Main {
    public  static void main(String[] args) {
         String s = "Z3X(XY)2";
        System.out.println(countChars(s));
    }
    public static String countChars(String input) {
        HashMap<Character, Integer> charCount = new HashMap<>();
        countCharsHelper(input, 1, charCount);
        String output = "";
        for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
            output += entry.getKey() + entry.getValue().toString();
        }
        return output;
    }

    private static void countCharsHelper(String input, int count, HashMap<Character, Integer> charCount) {
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '(') {
                int endIndex = findMatchingParenthesis(input, i);
                int num = getNumberAfterParenthesis(input, endIndex + 1);
                countCharsHelper(input.substring(i + 1, endIndex), count * num, charCount);
                i = endIndex + Integer.toString(num).length();
            } else if (Character.isLetter(c)) {
                int num = getNumberAfterParenthesis(input, i + 1);
                charCount.put(c, charCount.getOrDefault(c, 0) + count * num);
            }
        }
    }

    private static int findMatchingParenthesis(String input, int startIndex) {
        int count = 1;
        for (int i = startIndex + 1; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '(') {
                count++;
            } else if (c == ')') {
                count--;
                if (count == 0) {
                    return i;
                }
            }
        }
        return -1;
    }

    private static int getNumberAfterParenthesis(String input, int startIndex) {
        //数字可能不止个位
        int endIndex = startIndex;
        while (endIndex < input.length() && Character.isDigit(input.charAt(endIndex))) {
            endIndex++;
        }
        //可能只有是1
        return endIndex == startIndex ? 1 : Integer.parseInt(input.substring(startIndex, endIndex));
    }

}
